use image::RgbImage;
use rustface::{create_detector, ImageData};

pub fn check_face(img: &RgbImage) -> Result<(), String> {
    // 初始化检测器，传入模型文件路径
    let model_path = "E:\\研究项目\\Rust\\用Rust和egui 0.32.0写扫雷程序-扣子空间\\id_photo_checker\\target\\debug\\model\\seeta_fd_frontal_v1.0.bin";
    let mut detector =
        create_detector(model_path).map_err(|e| format!("人脸检测器初始化失败: {:?}", e))?;

    // 转换为灰度图像
    let gray_img = image::DynamicImage::ImageRgb8(img.clone()).to_luma8();
    let (width, height) = (gray_img.width(), gray_img.height());

    // 将图像数据转为 &[u8] 并正确构造 ImageData
    let buf: Vec<u8> = gray_img.into_raw();
    let image_data = ImageData::new(&buf, width, height);

    // 检测人脸
    let faces = detector.detect(&image_data);
    if faces.is_empty() {
        return Err("未检测到人脸".to_string());
    }

    // 验证人脸比例 (宽度占照片宽度的0.4-0.7)
    let face = &faces[0];
    let bbox = face.bbox(); // 获取人脸边界框
    let face_width = bbox.width() as f32;
    let photo_width = width as f32;
    let ratio = face_width / photo_width;

    if ratio < 0.4 || ratio > 0.7 {
        return Err(format!(
            "人脸比例不符合要求 (当前: {:.2}, 建议: 0.4-0.7)",
            ratio
        ));
    }

    Ok(())
}
